/**************************************************************
  > File Name: du_opendir.c
  > Author: LuoLiang
  > Mail: 1204553475@qq.com 
  > Created Time: 2021年12月19日 星期日 12时42分02秒
 **************************************************************/

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <dirent.h>

#define PATHSIZE 1024

//判断是否为..和.
static int is_loop(const char *pathname)
{
	char *pos = NULL;
	pos = strrchr(pathname,'/');
	if (pos == NULL)
		exit(1);
	if ((strcmp(pos+1,".") == 0) || (strcmp(pos+1,"..") == 0))
		return 0;
	return 1;
}


int64_t mydu(const char *filename)
{
	DIR *dir = NULL;
	struct dirent *dirres = NULL;
	static struct stat statbuff;
	int count = 0;
	int ret = 0;
	char fullpath[PATHSIZE] = {0};


	ret = lstat(filename,&statbuff);
	if (ret < 0)
	{
		perror("lstat()");
		exit(1);
	}
	if ((statbuff.st_mode & S_IFMT) != S_IFDIR)
	{
		return statbuff.st_blocks;
	}

	dir = opendir(filename);
	if (dir == NULL)
	{
		perror("opendir()");
		exit(1);
	}
	count = statbuff.st_blocks;

	while((dirres = readdir(dir)) != NULL)
	{
		//获得文件的完整路径			
		strncpy(fullpath,filename,PATHSIZE);
		strcat(fullpath,"/");
		strcat(fullpath,dirres->d_name);

		if (is_loop(fullpath))
			count += mydu(fullpath);
	}
	closedir(dir);
	return count;
}



int main(int argc,char **argv)
{
	if (argc < 2)
	{
		fprintf(stderr,"Usage\n");
		exit(1);
	}		
	
	printf("%ld\n",mydu(argv[1])/2);
    exit(0);
}
